package bid.yanhj.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bid.yanhj.common.service.FormatService;

/**
 * 日期工具类.
 * @author yanhaijiang
 *
 */
public class DateUtil {
    /**
     * log.
     */
    private static final Logger LOG = LoggerFactory.getLogger(DateUtil.class);
    /* 毫秒与秒间的转换. */
    private static final int DIFF = 1000;
    /**
     * 日期转换成字符串.
     * 
     * @param date 日期
     * @param pattern 日期格式
     * @return 转换后的日期字符串
     */
    public static String formatDate(Date date, String pattern) {
        if (date == null || StringUtils.isBlank(pattern)) {
            LOG.error(FormatService.logFormat("date[" + date + "] or pattern[" + pattern + "] is null."));
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }
    
    /**
     * 字符串转换为日期.
     * 
     * @param dateStr 日期字符串
     * @param pattern 日期格式
     * @return 转换后的日期
     */
    public static Date parseDate(String dateStr, String pattern) {
        if (StringUtils.isBlank(dateStr) || StringUtils.isBlank(pattern)) {
            LOG.error(FormatService.logFormat("dateStr[" + dateStr + "] or pattern[" + pattern + "] is null."));
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            LOG.error(
                    FormatService.logFormat("dateStr[" + dateStr + "] or pattern[" + pattern + "] has ParseException."),
                    e);
        }
        return null;
    }
    
    /**
     * 返回当前时间(秒).
     * 
     * @return 当前时间(秒)
     */
    public static int getCurrentSecond() {
        return (int) (Calendar.getInstance().getTime().getTime() / DIFF);
    }
    
    /**
     * 返回指定时间(秒).
     * 
     * @param date 日期
     * @return 指定时间(秒)
     */
    public static int getSecondByDate(Date date) {
        return (int) (date.getTime() / DIFF);
    }
    
    /**
     * 返回指定时间.
     * 
     * @param second 秒
     * @return 指定时间
     */
    public static Date getDateBySecond(int second) {
        return new Date(((long)second) * DIFF);
    }
    
    /**
     * 返回指定时间（字符串）.
     * 
     * @param second 秒
     * @param pattern 日期格式
     * @return 指定时间（字符串）
     */
    public static String getDateStrBySecond(int second, String pattern) {
        Date date = getDateBySecond(second);
        return formatDate(date, pattern);
    }
}
